package org.zfes.snowier.cloud.zbss.layer.tc.biz.auth;
import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.zfes.snowier.core.consts.SnowierWebConst;
import org.zfes.snowier.core.data.JSONMSG;
import org.zfes.snowier.core.util.ZDateUtil;
import org.zfes.snowier.core.util.ZStrUtil;
import org.zfes.snowier.core.util.ZWebUtil;
import org.zfes.snowier.core.util.datex.ZDateStyle;
import org.zfes.snowier.cloud.zbss.layer.tc.ZTCConfigProperties;
import org.zfes.snowier.cloud.zbss.layer.tc.biz.consts.BizConst;
public class AuhencFilter implements Filter{
	@Autowired
	ZTCConfigProperties configProperties;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request; 	
		HttpServletResponse httpResponse = (HttpServletResponse) response; 	
		String url=httpRequest.getRequestURI().trim();
		
		if(PathMach.pathsMatch("/static/**", url)){
			chain.doFilter(httpRequest, httpResponse);
			return;
		}
		if(PathMach.pathsMatch("/auth/doLogin", url)||PathMach.pathsMatch("/auth/logout", url)||url.contains("login")||url.contains("login.html")||url.contains("/static")){
			chain.doFilter(httpRequest, httpResponse);
			return;
		}
		Object sessonuser=httpRequest.getSession().getAttribute(BizConst.SESSION_USER);
		if(sessonuser==null){
			onAuthenticationUnAuthec(httpRequest,httpResponse);
			return;
		}
	
		String datexs=configProperties.getExpireDate();
		if(ZStrUtil.hasText(datexs)){
			Date expireDate=ZDateUtil.parseDate(datexs, ZDateStyle.YYYY_MM_DD);
			if(expireDate.before(new Date())){
				System.out.println("=====================");
				onAuthenticationUnAuthec(httpRequest,httpResponse);
			}
		}
		chain.doFilter(httpRequest, httpResponse);
	}
	public void onAuthenticationUnAuthec(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {
		if(ZWebUtil.isAjax(request)){
			ZWebUtil.respJSON(response, JSONMSG.newMSG(SnowierWebConst.SC.SC_401, "未登录"));
			return;
		} 
		String contextPath=((HttpServletRequest)request).getContextPath();  
		response.sendRedirect(contextPath+"/login.html?e=2");
	}
	
	@Override
	public void destroy() {
		
	}

	public ZTCConfigProperties getConfigProperties() {
		return configProperties;
	}

	public void setConfigProperties(ZTCConfigProperties configProperties) {
		this.configProperties = configProperties;
	}


	 
	 
}
